package ua.races.command.implementation;

import org.apache.log4j.Logger;
import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import ua.races.vo.Horse;
import ua.races.vo.Race;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class PrepareAddRaceCommand implements ServletCommand {
    private static final Logger log = Logger.getLogger(PrepareAddRaceCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        RacesDaoImpl dao;
        dao = (RacesDaoImpl) context.getAttribute("DAO");
        Integer numberOfHorses = null;
        String redirectUrl = null;
        List<Horse> horses = null;
        Set<String> stadiums = null;
        List<Race> races = null;

        try {
            redirectUrl = req.getHeader("referer");
            numberOfHorses = Integer.parseInt(req.getParameter("numberOfHorses"));
            horses = dao.findAllHorses();
            races = dao.findAllRaces();
            stadiums = new HashSet<String>();
            for (Race r : races) {
                stadiums.add(r.getStadium());
            }
            if (numberOfHorses == null || numberOfHorses <= 0) {
                redirectUrl = req.getHeader("referer");
                throw new IllegalArgumentException("invalid number of horses");
            }
            req.setAttribute("numberOfHorses", numberOfHorses);
            req.setAttribute("horses", horses);
            req.setAttribute("stadiums",stadiums);
            redirectUrl = "/addRace.jsp";
            log.info("addRace.jsp successfully prepared");
        } catch (SQLException e) {
            log.error(e);
        } catch (Throwable e) {
            log.error(e);
           try {
                resp.sendRedirect("/pipec.jsp");
            } catch (IOException e1) {
               log.fatal(e1);
            }
        } finally {
            try {
                context.getRequestDispatcher(redirectUrl).forward(req, resp);
            } catch (ServletException e) {
                log.error(e);
            } catch (IOException e) {
                log.error(e);
            }
        }

    }


}